import { PlusOutlined, UploadOutlined } from "@ant-design/icons";
import { Modal, Upload, Button, message, Image } from "antd";
import type { RcFile, UploadProps } from "antd/es/upload";
import type { UploadFile } from "antd/es/upload/interface";
import { useState, useEffect, forwardRef, useImperativeHandle, useRef } from "react";
import { store } from "@/redux";
import { FileItemModel } from "@/api/interface/index";
import "./index.less";
// 继承UploadFile的listType属性
interface CustomUploadFile extends UploadFile {
	id: number;
}
// 定义暴露方法的类型
export interface CuploadImageMethods {
	clearFileList: () => void;
}
/**
 * 自定义上传图片组件
 * @param max 最大上传数量
 * @param defaultFileList 默认文件列表
 * @param onChangeIds 回调函数，上传成功后返回文件id数组
 * @param onStatusChange 回调函数，上传状态改变后返回状态
 * @returns
 */
interface CuploadImageProps {
	max?: number; // 最大上传数量
	width?: number;
	height?: number;
	defaultFileList?: FileItemModel[]; // 默认文件列表
	onChangeIds?: (ids: string[]) => void; // 回调函数，上传成功后返回文件id数组
	onStatusChange?: (status: "success" | "error") => void; // 回调函数，上传状态改变后返回状态
}
// { max, defaultFileList, onChangeIds, onStatusChange }: CuploadImageProps
const CuploadImage = forwardRef<CuploadImageMethods, CuploadImageProps>((_props: CuploadImageProps, ref) => {
	const { max, defaultFileList, width = 100, height = 100, onChangeIds, onStatusChange } = _props;
	CuploadImage.displayName = "CuploadImage";
	// 上传地址 && token
	const [headers] = useState<{ token: string }>({ token: store.getState().global.token });
	const [action] = useState(`${import.meta.env.VITE_API_URL as string}/fileHandle/uploadImage`);

	const [fileList, setFileList] = useState<CustomUploadFile[]>([]);
	// 初始化复制默认文件列表
	useEffect(() => {
		if (defaultFileList && defaultFileList.length > 0) {
			setFileList(
				defaultFileList.map((item: FileItemModel, index: number) => ({
					...item,
					uid: `-${index}`,
					status: "done",
					thumbUrl: item.url
				})) as CustomUploadFile[]
			);
			console.log(defaultFileList, "defaultFileList");
		}
	}, [defaultFileList]);
	const handleChange: UploadProps["onChange"] = info => {
		let newFileList: CustomUploadFile[] = [...info.fileList] as CustomUploadFile[];

		newFileList = newFileList
			.map(file => {
				const { response } = file;
				// 处理本地上传的文件
				if (response) {
					const { data, code } = response;
					if (code === 0) {
						// 由于 CustomUploadFile 接口扩展了 UploadFile 并添加了 id 属性，
						// 因此将 file 类型断言为 CustomUploadFile 以解决类型错误
						file.id = data.id;
					}
				}
				return file.status ? file : undefined; // 过滤掉没有状态的文件
			})
			.filter(file => file !== undefined) as CustomUploadFile[];
		console.log(newFileList, "newFileList");
		// 判断是否上传错误
		const isError = newFileList.findIndex(file => file.error);
		if (isError !== -1) {
			newFileList[isError].thumbUrl = "";
			message.error("上传失败");
		}
		// 判断是否存在未上传或错误的文件
		const isAllSuccess = newFileList.every(file => file.status === "done" && !file.error);
		if (isAllSuccess) {
			onChangeIds && onChangeIds(newFileList.map(item => item.id.toString()));
			onStatusChange && onStatusChange("success");
			console.log(
				"全部上传成功，提交数据:",
				newFileList.map(item => item.id)
			);
		} else {
			onStatusChange && onStatusChange("error");
			console.error("存在未完成或失败的文件");
		}
		setFileList(newFileList);
	};
	const handleBeforeUpload = (file: RcFile) => {
		// 限制上传文件的大小为 5MB
		const isLt5M = file.size / 1024 / 1024 < 5;
		if (!isLt5M) {
			message.error("文件大小不能超过 5MB!");
			return false;
		}
		return isLt5M;
	};
	// 定义要暴露的方法
	useImperativeHandle(ref, () => ({
		clearFileList: () => {
			console.log("执行子组件方法");
			setFileList([]);
			onChangeIds && onChangeIds([]);
			onStatusChange && onStatusChange("success");
		}
	}));
	const props = {
		action: action,
		headers: headers,
		onChange: handleChange,
		beforeUpload: handleBeforeUpload,
		multiple: true
	};
	const uploadButton = (
		<div>
			<PlusOutlined className="text-20" />
			<div style={{ marginTop: 2 }}>上传</div>
		</div>
	);
	const [previewVisible, setPreviewVisible] = useState<boolean>(false);
	const [currentSrc, setCurrentSrc] = useState<string | undefined>("");
	return (
		<div className="CuploadImage" style={{ width: width, height: height }}>
			<Upload
				{...props}
				fileList={fileList}
				listType="picture-card"
				accept="image/*"
				onPreview={file => {
					// 自定义预览逻辑（如弹窗显示大图）
					setPreviewVisible(true);
					setCurrentSrc(file.thumbUrl);
				}}
			>
				{max && fileList.length >= max ? null : uploadButton}
			</Upload>
			{/* 大图预览 */}
			<Image
				style={{ display: "none" }}
				src={currentSrc}
				preview={{
					visible: previewVisible,
					onVisibleChange: visible => setPreviewVisible(visible)
				}}
			/>
		</div>
	);
});

export default CuploadImage;
